<template>
  <div >

      <!-- 各类成果占比卡片 -->

        <el-card shadow="hover" class="custom-card">
          <div class="card-content">
            <div class="card-left">
              <div class="card-title"> <i class="el-icon-collection-tag"></i>​​成果类型分布​</div>
              <div ref="achievementChart" class="chart-container"></div>
            </div>
          </div>
        </el-card>


  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getPatentInfoForCard } from "@/api/sci/patent";
import { getSoftwareCopyrightForCard} from "@/api/sci/copyright";
import { getPaperInfoForCard } from "@/api/sci/paper";
import { getStandardInfoForCard } from "@/api/sci/standard";

export default {
  name: "AchvRatio",
  components: {},
  data() {
    return {
      growthRate: 60,
      patentData: {
        all_count: 0,
        current_count: 0,
        growth_rate: 0
      },
      copyrightData: {
        all_count: 0,
        current_count: 0,
        growth_rate: 0
      },
      paper: {
        all_count: 0,
        current_count: 0,
        growth_rate: 0
      },
      standard: {
        all_count: 0,
        current_count: 0,
        growth_rate: 0
      },
      chart: null
    };
  },
  computed: {

  },
  created() {
    this.fetchAllData();
  },
  mounted() {
    this.initChart();
  },
  watch: {},
  methods: {
    async fetchAllData() {
      try {
        // 获取所有数据
        const [patentRes, copyrightRes, paperRes, standardRes] = await Promise.all([
          getPatentInfoForCard(),
          getSoftwareCopyrightForCard(),
          getPaperInfoForCard(),
          getStandardInfoForCard()
        ]);

        this.patentData = patentRes.data;
        this.copyrightData = copyrightRes.data;
        this.paper = paperRes.data;
        this.standard = standardRes.data;

        // 数据获取完成后更新图表
        this.$nextTick(() => {
          this.updateChart();
        });
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取成果数据失败");
      }
    },

    initChart() {
      // 初始化图表
      this.chart = echarts.init(this.$refs.achievementChart);
      this.updateChart();

      // 监听窗口变化，自适应调整图表大小
      window.addEventListener('resize', this.handleResize);
    },

    updateChart() {
      if (!this.chart) return;

      // 计算总数用于百分比计算
      const total = (this.patentData.all_count || 0) +
                    (this.paper.all_count || 0) +
                    (this.copyrightData.all_count || 0) +
                    (this.standard.all_count || 0);

      // 计算各项百分比
      const patentPercent = total ? ((this.patentData.all_count || 0) / total * 100).toFixed(1) : 0;
      const paperPercent = total ? ((this.paper.all_count || 0) / total * 100).toFixed(1) : 0;
      const copyrightPercent = total ? ((this.copyrightData.all_count || 0) / total * 100).toFixed(1) : 0;
      const standardPercent = total ? ((this.standard.all_count || 0) / total * 100).toFixed(1) : 0;

      const option = {
        color: ['#267FF7', '#7AB8FF', '#599EEC', '#3673E8'],
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(38, 127, 247, 0.15)', // 淡蓝色背景
          borderColor: 'rgba(64, 158, 255, 0.3)', // 边框颜色
          borderWidth: 1,
          padding: 10,
          textStyle: {
            color: '#000',
            fontSize: 12
          },
          extraCssText: 'backdrop-filter: blur(10px); border-radius: 8px; box-shadow: 0 0 20px rgba(64, 158, 255, 0.3);',
          formatter: (param) => {
            return `<div style="padding: 8px 12px; background: rgba(255, 255, 255, 0.1); border-radius: 6px; margin-bottom: 8px; font-weight: bold; text-align: center;">${param.name}</div>
                    <div style="padding: 6px 10px; background: ${param.color}; border-radius: 5px; display: flex; justify-content: space-between; align-items: center;">
                      <div>
                        <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${param.color}; margin-right: 6px;"></span>
                        <span style="color:#ffffff">数量</span>
                      </div>
                      <span style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 15px;">${param.value}</span>
                    </div>`;
          }
        },
        legend: {
          orient: 'horizontal',
          bottom: '0',

          data: ['专利', '论文', '软著', '标准'],

        },
        series: [
          {
            name: '成果类型',
            type: 'pie',
            radius: ['45%', '60%'],
            center: ['50%', '48%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: (params) => {
                // 计算百分比
                const total = params.data.value || 0;
                const allTotal = (this.patentData.all_count || 0) +
                                (this.paper.all_count || 0) +
                                (this.copyrightData.all_count || 0) +
                                (this.standard.all_count || 0);
                const percentage = allTotal ? ((total / allTotal) * 100).toFixed(1) : 0;

                // 返回带格式的标签文本
                return `{name|${params.name}}{gap| }{value|${total}}{gap| }{percent|${percentage}%}`;
              },
              position: 'outside',
              alignTo: 'none',
              bleedMargin: 5,
              distanceToLabelLine: 5,
              textStyle: {
                fontSize: 12
              },
              rich: {
                name: {
                  color: '#666666',
                  fontSize: 12,
                  padding: [0, 0, 0, 0]
                },
                value: {
                  color: '#2559B2',
                  fontSize: 12,
                  fontWeight: 'bold',
                  textShadowColor: 'rgba(37, 89, 178, 0.3)',
                  textShadowBlur: 2,
                  textShadowOffsetX: 1,
                  textShadowOffsetY: 1,
                  padding: [0, 5, 0, 5]
                },
                percent: {
                  color: '#999999',
                  fontSize: 12,
                  fontWeight: 'bold',
                  padding: [0, 0, 0, 5]
                },
                gap: {
                  width: 4,
                  height: 14,
                  backgroundColor: 'transparent'
                }
              }
            },
            labelLine: {
              show: true
            },
            // label: {
            //   show: false,
            //   position: 'center'
            // },
            //  labelLine: {
            //   show: false
            // },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },

             data: [
              {
                value: this.patentData.all_count || 0,
                name: '专利',

              },
              {
                value: this.paper.all_count || 0,
                name: '论文',

              },
              {
                value: this.copyrightData.all_count || 0,
                name: '软著',

              },
              {
                value: this.standard.all_count || 0,
                name: '标准',

              }
            ]
          }
        ]
      };

      this.chart.setOption(option);
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },

  beforeDestroy() {
    // 销毁图表实例，防止内存泄漏
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="scss" scoped>

  .chart-container {
    width: 100%;
    height: 200px;
     min-height: 200px;
  }

  .custom-card {
    border-radius: 8px;
    border: none;

    ::v-deep .el-card__body {
      padding: 20px;
    }
  }

  .card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-left {
    flex: 1;
  }

   .card-title {
    color: #000000;
    font-size: 22px;
    margin-bottom: 16px;
    font-weight: bold; /* Changed to bold */
    font-family: SimHei, sans-serif; /* Added SimHei font */
    display: flex;
    align-items: center;
    gap: 15px;
  }


</style>
